import re
import requests
import base64
import os
from pymongo import MongoClient

'''
导入Mongodb前先清空集合
Mongodb,price集合：所有价格
Mongodb,overview集合：每日总价和数量
'''


def dropCollect():
    client = MongoClient('127.0.0.1')
    db = client['meicai']
    colPrice = db['price']
    colOverview = db['overview']
    colPrice.drop()
    colOverview.drop()

# 导入图片


def read_pics(path):
    for root, dirs, files in os.walk(path):
        files = [i for i in files if i.endswith('.jpeg')]
        for name in files:
            filename = os.path.join(root, name)
            # filename=路径/文件名,路径代表日期fileMonth
            #fileData = (filename.split('/')[-2])
            # 循环每张图片文件调用百度接口，传入文件名filename参数
            recognize_baidu(filename)

            # print(results)


# 调用百度文字识别函数


def recognize_baidu(filename):
    # print(filename)
    # f = open(r'/mic/python/sushitime/3月/1/2019030101.jpeg', 'rb')
    # filename=路径/文件名,路径代表日期fileMonth
    fileDate = (filename.split('/')[-2])
    f = open(filename, 'rb')

    # 图片需要64位编码
    img = base64.b64encode(f.read())
    # 上传类型为img
    data = {'image': img}
    # token30天更新一次
    access_token = '24.08cc35b7d266d24d997c44d6a953021e.2592000.1554875954.282335-15719236'
    url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token='+access_token

    headers = {
        'Content-Type': 'application/x-www-form-urlencoded'
    }
    # requests模块post方法提交数据
    r = requests.post(url, headers=headers, data=data)
    # 返回格式为json
    s = r.json()
    # 返回的json结果放到列表中
    recognize_items = [line['words'] for line in s['words_result']]
    # 返回数据待调用
    # print(filename)
    # print(recognize_items)
    # return(recognize_items)
    # 调用提取数字函数filter_items
    filter_items(recognize_items, fileDate)

# 提取数字函数


def filter_items(food_list, fileDate):
    # items_test文件中定了了3列，分别是需提取的货物名称，商品金额的小数位，商品数量的小数位，共3个值，写入item_list列表中。
    items_list = [line.split(' ', 2) for line in open(
        '/mic/python/sushitime/items_test.txt')]
    # 调用文字识别的函数数据至列表food_list
    # food_list = recognize_baidu()
    # 用items_list的数据匹配food_list
    # print(food_list)

    # 每张图片不一定都有付款总金额，如没有获取到使用try忽略该图片
    try:
        totalPaymentName = '下单商品金额'
        # 获取当前值的索引+1，获取对应的价格
        totalPaymentPrice = food_list[food_list.index(totalPaymentName)+1]
        # print('总价'+totalPaymentPrice)
        # re.sub替换人民币符合为空
        totalPaymentPrice = re.sub('￥', '', totalPaymentPrice)
        # print('总价'+totalPaymentPrice)
    # 获取不到直接填0，在数据库里合并同一天的值
    except:
        totalPaymentPrice = 0

    # 每张图片不一定都有获取订单总件数
    try:
        # re.findall搜索关键字‘共+数字’
        match = re.findall(r'共\d+', str(food_list))
        # 从match再次获取捕获的数字
        totalNumber = re.findall(r'\d+', match[0])
        # print(totalNumber[0])
        totalNumber = totalNumber[0]

    except:
        totalNumber = 0
    # 数据插入mongodb
    insertMongoOverview(fileDate, totalPaymentPrice, totalNumber)

    # 从定义的原料(items_list)列表中循环搜索百度识别后的商品列表(food_list)
    for i in items_list:
        for j in food_list:
            '''
            百度识别的误差会导致小数点位数不对，需要重新过滤
            items_list定义的商品(三个字段：商品名，价格的小数点前位数，数量的小数点前位数)
            '''
            if i[0] in j:
                # 打印文字识别后的名称，也可以打印自定义名称
                print('商品名:'+j)

                if '赠' in j:
                    print(j)
                    # 仅插入赠送商品名称
                    insertMongo(
                        fileDate, i[0], j, 0, 0)
                    # 跳出本次循环
                    continue

                # 获取识别的名称对应的索引值
                s = food_list.index(j)
                # 在商品名称后面的3索引数据中查找收款金额数据，因收款索引值不固定
                for m in range(3):
                    next_items = m+1+s
                    # 获取对应的列表值
                    # 防止截图没截全，取不全价格导致程序报错
                    try:
                        price = food_list[next_items]
                        print(price)
                    except:
                        pass
                    # 如果值包含'收'，但不包含'等额收货',既为需要的值
                    if '收' in price and '等额收货' not in price:
                        # print(price)
                        # try:
                        # 分割数据分别获取金额totalPrice和数量totalQuality
                        # 防止百度没有识别出'/'
                        try:
                            # if '/' in price:
                            (totalPrice, totalQuality) = price.split('/')
                            '''
                            else:
                                totalPrice = 0
                                print(totalQuality)
                                totalQuality = re.findall(r'\d+\.*\d+', price)
                            '''
                            # print(totalPrice)
                        except:
                            pass
                        # 用正则表达式金额匹配数字(至少有一个数字，可有无小数点，再接至少一个数字 1.1 11)
                        totalChangePrice = re.findall(
                            r'\d+\.*\d+', totalPrice)
                        # 用正则表达式匹配数量数字，数量有整数
                        totalChangeQuality = re.findall(
                            r'(\d+\.*\d*)', totalQuality)
                        # print(totalQuality)
                        # print(totalChangeQuality[0])
                        # print(type(totalChangeQuality[0]))
                        # print(type(totalChangeQuality[0]))
                        # print(totalChangeQuality)
                        # 调用小数点过滤函数修正金额数据，传入items_list定义的第二位数据，和价格。
                        totalEndPrice = check_decimalPoint(
                            i[1], (totalChangePrice[0]))
                        # 打印修正后的价格

                        # print('价格:'+totalEndPrice)

                        # print(totalQuality)
                        # '袋',‘盒’单位没有小数点，所以文字识别不会有错，不需要修正
                        # if '袋'in totalQuality or '盒' in totalQuality or '罐' in totalQuality or '箱' in totalQuality:
                        if ('袋' or '盒' or '罐' or '箱') in totalQuality:
                            # print('数量:'+totalQuality)
                            insertMongo(
                                fileDate, i[0], j, totalEndPrice, totalQuality)

                        else:
                            # print(totalChangeQuality)
                            # 调用小数点过滤函数修正数量数据，传入自定义items_list的第三位数据和数量
                            totalEndQuality = check_decimalPoint(
                                i[2], (totalChangeQuality[0]))
                        # 打印修正后的数量
                            # print('数量:'+totalEndQuality)
                            insertMongo(fileDate, i[0], j, totalEndPrice,
                                        totalEndQuality)

                        # except:
                        #    pass

# 小数点修正函数


def check_decimalPoint(num, price):
    # 匹配金额中是否有小数点，并用传入的num来确定小数点的位置是否正确
    pattern = re.compile(r'\d{%s}\.' % num)
    result = pattern.match(str(price))
    # 如果正确直接返回价格
    if result:
        return(price)
    else:
        # 如果错误
        # print('def:'+num+price)
        split_list = list(str(price))
        for i in split_list:
            if i == '.':
                removeIndex = split_list.index(i)
                split_list.pop(removeIndex)
        split_list.insert(int(num), '.')
        result = ''.join(split_list)
        return(result)


# s = check_decimalPoint(1, 6.1)
# print(s)


def insertMongo(date, name, meicainame, price, quality):
    client = MongoClient('127.0.0.1')
    db = client['meicai']

    col = db['price']
    col.insert_one({'date': date, 'name': name, 'meicainame': meicainame,
                    'price': price, 'quality': quality})


def insertMongoOverview(date, totalPrice, totalNumber):
    client = MongoClient('127.0.0.1')
    db = client['meicai']
    col = db['overview']
    col.insert_one({'date': date, 'totalprice': totalPrice,
                    'totalnumber': totalNumber})


def cleanDb():
    client = MongoClient('127.0.0.1')
    db = client['meicai']
    colNewPrice = db['price']
    colNewPrice.drop()
    colNewPrice = db['newprice']


if __name__ == '__main__':
    dropCollect()
    truePath = '/mic/python/sushitime/3月/20'
    read_pics(truePath)
    # filter_items()
